package com.kiven.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 解压缩Zip文件<br><br>
 * Example:<br>
 * String targetPath = "/home/lijianbo/kivenTest/status";<br>
 * String zipFilePath = "/home/lijianbo/kienTest/status/test.xml.zip";<br>
 * Zip unzipFile(targetPath,zipFilePath);<br>
 * @author liqingwen
 *
 */

public class Unzip {
	/**
	 * 
	 * @param targetPath 解压缩目标路劲
	 * @param zipFilePath	待解压缩文件
	 * 
	 */
	public void unzipFile(String targetPath,String zipFilePath) {
		try {
			File zipFile = new File(zipFilePath);
			InputStream is = new FileInputStream(zipFile);
			ZipInputStream zis = new ZipInputStream(is);
			ZipEntry entry = null;
			
			//循环解压缩所用文件
			while((entry = zis.getNextEntry()) != null) {
				String zipPath = entry.getName();
				
				//解压文件夹
				if(entry.isDirectory()) {
					File zipFolder = new File(targetPath + File.separator + zipPath);
					if(!zipFolder.exists()) {
						zipFolder.mkdirs();
					}
				}
				else {
					//解压文件
					File file = new File(targetPath + File.separator + zipPath);
					if(!file.exists()) {
						File pathDir = file.getParentFile();
						pathDir.mkdirs();
						file.createNewFile();
					}
					
					FileOutputStream fos = new FileOutputStream(file);
					int bread;
					if((bread = zis.read()) != -1) {
						fos.write(bread);
					}
					fos.close();
				}
			}
			zis.close();
			is.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String targetPath = "/home/lijianbo/kivenTest";
		String zipFilePath = "/home/lijianbo/kivenTest/city.zip";
		new Unzip().unzipFile(targetPath, zipFilePath);
	}
}
